package com.zhaoyue.study.concurrency.thread.threadfactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;

/**
 * Created with IntelliJ IDEA.
 * User: zhaoyue
 * Date: 2016/9/6
 * Time: 13:32
 * 线程工厂
 */
public class MyThreadFactory implements ThreadFactory {

    private int count;
    private String name;
    private List<String> stats;

    public MyThreadFactory(String name){
        this.name = name;
        count = 0;
        stats = new ArrayList<String>();
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(r,name + "Thread_" + count);
        count ++;
        stats.add(String.format("created thread %d with name %s on %s\n",t.getId(),t.getName(),new Date()));
        return t;
    }

    public String getStats(){
        StringBuffer buffer=new StringBuffer();
        Iterator<String> it=stats.iterator();
        while (it.hasNext()) {
            buffer.append(it.next());
            buffer.append("\n");
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        MyThreadFactory myThreadFactory = new MyThreadFactory("myThreadFactory");
        Task task = new Task();
        Thread thread = null;
        for(int i=0;i<5;i++){
            thread = myThreadFactory.newThread(task);
            thread.start();
        }
        System.out.printf("Factory stats:\n"); System.out.printf("%s\n",myThreadFactory.getStats());
    }
}
